package com.zxtech.zzm.zxmonitorsocket

import android.util.Log
import com.zxtech.zzm.core.util.CodecUtil
import com.zxtech.zzm.core.util.DeviceUtil

class SocketPackageSend private constructor(builder: Builder) {
  private val packageHead = "CLTC".toByteArray()
  private var packageLength: ByteArray? = ByteArray(2)
  private var type: Byte? = null
  private var idBytes: ByteArray? = ByteArray(7)
  private var data: ByteArray? = null

  init {
    data = builder.getData()
    type = builder.getType()
    idBytes = builder.getIDBytes()
    packageLength = builder.getPackageLength()
  }

  fun buildPackage(): ByteArray {
    val length = 4 + 2 + 1 + 7 + data!!.size
    val sendpackage = ByteArray(length)
    System.arraycopy(packageHead, 0, sendpackage, 0, 4)
    System.arraycopy(packageLength, 0, sendpackage, 4, 2)
    System.arraycopy(byteArrayOf(type!!), 0, sendpackage, 6, 1)
    idBytes?.let { Log.e("zzm debug", "idBytes :" + CodecUtil.formatHexString(it)) }
    if (idBytes == null || idBytes!!.isEmpty()) {
      System.arraycopy(
          DeviceUtil.getTerminalID()
              .toByteArray(), 0, sendpackage, 7, 7
      )
    } else {
      System.arraycopy(idBytes, 0, sendpackage, 7, 7)
    }
    System.arraycopy(data, 0, sendpackage, 14, data!!.size)
    return sendpackage
  }

  /**
   * 构建器
   */
  class Builder {
    private var packageLength: ByteArray? = null
    private var type: Byte = 0
    private var idBytes: ByteArray? = null
    private var data: ByteArray? = null
    fun getData(): ByteArray? {
      return data
    }

    fun getIDBytes(): ByteArray? {
      return idBytes
    }

    fun getType(): Byte {
      return type
    }

    fun getPackageLength(): ByteArray? {
      return packageLength
    }

    fun setPackageLength(packageLength: ByteArray): Builder {
      this.packageLength = packageLength
      return this
    }

    fun setPackageLength(
      b1: Byte,
      b2: Byte
    ): Builder {
      packageLength = byteArrayOf(b1, b2)
      return this
    }

    fun setType(type: Byte): Builder {
      this.type = type
      return this
    }

    fun setIdBytes(idBytes: ByteArray): Builder {
      this.idBytes = idBytes
      return this
    }

    fun setData(data: ByteArray): Builder {
      this.data = data
      return this
    }

    fun setData(data: Byte): Builder {
      this.data = byteArrayOf(data)
      return this
    }

    fun build(): SocketPackageSend {
      return SocketPackageSend(this)
    }
  }
}